//
//  ZP_URLRouter.swift
//  ZP_URLRouter
//
//  Created by zhangpoor on 17/2/27.
//  Copyright © 2017年 zhangpoor. All rights reserved.
//

import UIKit



public class ZP_URLRouter: NSObject
{
    
    static var routerInfo:[String:Any]? = nil
    
    static func loadUrlRouterInfo() -> Bool
    {
        if ZP_URLRouter.routerInfo == nil
        {
            let fileUrl = Bundle.main.resourcePath! + "/ZP_RouterInfo.plist"
            
            ZP_URLRouter.routerInfo = NSDictionary(contentsOfFile: fileUrl) as? [String:Any]
            
            NSLog("ZP_URLRouter_===========> Load RouterInfo <============")
            NSLog("ZP_URLRouter_fileUrl:\(fileUrl)")
            NSLog("ZP_URLRouter_info:\(routerInfo)")
        }
        
        return ZP_URLRouter.routerInfo != nil
    }
    
    
    static func checkUrl(_ url:String ) -> (ZP_RouterModel?,String?)
    {
        var model:ZP_RouterModel?
        var eMsg:String?
        
        if ZP_URLRouter.loadUrlRouterInfo()
        {
            if let info = ZP_URLRouter.routerInfo?["URLSchemes"] as? [String]
            {
                for item in info
                {
                    if url.hasPrefix(item+"://")
                    {
                        let m       = ZP_RouterModel()
                        
                        m.oUrl      = url
                        m.urlHead   = item
                        m.rUrl      = url.substring(from: (item+"://").endIndex )
                        if let u =  getStringBeforeChar(m.rUrl, "?") {
                            m.rUrl      = u
                        }
                        
                        let pStr = getStringAfterChar(m.rUrl, "&") //？号后面第一个 & 符号起，不包括第一个&
                        
                        
                        if let pAry = pStr?.components(separatedBy: "&")
                        {
                            for p in pAry
                            {
                                let kv:[String] = p.components(separatedBy: "=")
                                if kv.count == 2 {
                                    m.params[kv[0]] = kv[1]
                                }
                                
                            }
                        }

                        model = m

                        break
                    }
                }
                
                if model == nil {
                    eMsg = "未找到相关路径头"
                }
            }
            else
            {
                eMsg = "未能读取到路径头信息"
            }
        }
        else
        {
            eMsg = "未能读取到总路径信息"
        }
        
        return (model,eMsg)
        
    }
    
    
    /*
    static func checkUrl(_ url:String , _ callback:((ZP_RouterModel?,String?)->Void)? )
    {
        var model:ZP_RouterModel?
        var eMsg:String?

        if ZP_URLRouter.loadUrlRouterInfo()
        {
            if let info = ZP_URLRouter.routerInfo?["URLSchemes"] as? NSArray
            {

                for item in info
                {
                    if let head = item as? String , url.hasPrefix(head+"://")
                    {
                        
                        let m       = ZP_RouterModel()
                        m.rUrl      = url.substring(from: (head+"://").endIndex )
                        m.oUrl      = url
                        m.urlHead   = head

                        
                        
                        model = m
                        
                        
                        
                        break
                    }
                }
                
                if model == nil {
                    eMsg = "未找到相关路径头"
                }
            }
            else
            {
                eMsg = "未能读取到路径头信息"
            }
        }
        else
        {
            eMsg = "未能读取到总路径信息"
        }
        
        if let cb = callback {
            cb(model,eMsg)
        }
        
    }
    */
    static func createRouterModel(_ url:String) -> (ZP_RouterModel? ,String?)
    {
        var (result,resultStr) = checkUrl(url)
        
        if resultStr == nil {
            if let rInfo = ZP_URLRouter.routerInfo?["BizInfos"] as? [String:Any]
            {
                for (k,v) in rInfo
                {
                    
                    if let model = result , k == model.rUrl , let d = v as? [String:String]
                    {
                        model.name      = d["name"]
                        model.tClass    = d["class"]
                        model.tHandler  = d["handler"]
                        
                        break
                    }
                }
                
                if result?.tClass == nil && result?.tHandler == nil
                {
                    resultStr = "未能找到路径对应的映射信息"
                }
            }
            else
            {
                resultStr = "未找到路径信息"
            }
        }


        
        
        return (result,resultStr)
        
    }
    
    public static func open(_ rootController:UIViewController? , _ url:String) -> Void
    {
        let (rInfo,eMsg) = createRouterModel(url)
        
        if let e = eMsg {
            
            print("open:    url-\(url)  eMsg-\(e)")
            
            return
        }
  
        if  let tC = rInfo?.tClass ,  let tVC = viewControllerFromString(tC) {
            
            var rVc:UIViewController? = rootController
            
            if rVc == nil
            {
                rVc = UIApplication.shared.keyWindow?.rootViewController
            }
            
            if let vc = rVc {
                if let nav = vc.navigationController
                {
                    nav.pushViewController(tVC, animated: true)
                    
                }
                else
                {
                    vc.present(tVC, animated: true, completion: {
                        
                    })
                }
            }
   
        }
     
    }
}
